<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class PackageProduct extends Model
{
    public function packData(): HasOne
    {
        return $this->hasOne(Package::class, 'id', 'pack');
    }

    public function attrData(): HasOne
    {
        return $this->hasOne(PackageAttr::class, 'id', 'attr');
    }

    public function productData(): HasOne
    {
        return $this->hasOne(Product::class, 'id', 'product');
    }

    public function addPackData()
    {
        $param = request()->post();
        $this->where(['pack' => $param['pack']])->delete();
        $product = [];
        //去除重复产品
        foreach ($param['product'] as $key => $value) {
            unset($value['id'], $value['create_time'], $value['update_time']);
            $key = "{$value['product']}-{$value['attr']}";
            if (!isset($product[$key])) $product[$key] = $value;
        }
        return $this->saveAll(array_values($product));
    }
}
